package global

import (
	"chat/config"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"os"
	"time"
)

var (
	DB      *gorm.DB
	Logger  *logrus.Logger
	FileSet = map[string]bool{".png": true, ".jpg": true, ".jpeg": true, ".gif": true}
)

func InitLogger() error {
	logger := logrus.New()
	logger.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
	path := config.GetConfig().App.LogSavePath

	if config.GetConfig().Server.RunMode == "release" {
		err := os.MkdirAll(path, 0666)
		if err != nil {
			return err
		}
		writer, _ := rotatelogs.New(path+".%Y%m%d%H%M",
			rotatelogs.WithLinkName(path),
			rotatelogs.WithMaxAge(time.Duration(168)*time.Hour),
			rotatelogs.WithRotationTime(time.Duration(720)*time.Hour))
		logger.SetOutput(writer)
		logger.SetFormatter(&logrus.JSONFormatter{})
	}

	logger.SetReportCaller(true)
	Logger = logger
	return nil
}
